import {Session} from '@/utils/storage';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {
  createRouter, createWebHashHistory,
  createWebHistory,
  RouteLocationNormalized,
  RouteLocationNormalizedLoaded,
  RouteLocationRaw,
  Router
} from 'vue-router';
import routes from './routes';
import {ElMessage} from "element-plus";
const { VITE_TOKEN_KEY, VITE_TITLE, VITE_UID_KEY } = import.meta.env;
const scrollBehavior = function (
  to: RouteLocationNormalized,
  from: RouteLocationNormalizedLoaded,
  savedPosition: Record<string, any> | null
) {
  if (savedPosition) {
    return savedPosition;
  } else {
    const position: Record<string, any> = {};
    if (to.hash) {
      position.el = to.hash;
      position.behavior = 'smooth';
      if (to.name == 'Item') {
        position.top = 200;
      }
      if (/^#\w/.test(to.hash) || document.querySelector(to.hash)) {
        return position;
      }
      return false;
    }
    return new Promise((resolve) => {
      if (to.matched.some((m) => m.meta.scrollToTop)) {
        position.left = 0;
        position.top = 0;
      }
      resolve(position);
    });
  }
};

const router: Router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
  scrollBehavior
});

// authList
const whiteList: Array<string> = ['/authentication', '/login'];
router.beforeEach( (to, from, next) => {
  const token = Session.get('ZJ_token');
  console.log('asdkasjdkasjid ')
  if (whiteList.some((item) => to.path === item) && !token) {
    next();
    NProgress.done();
  } else {
    if (!token) {
      next(`/login`);
      Session.clear();
      NProgress.done();
    } else if (token && to.path === '/login') {
      next('/home');
      NProgress.done();
    } else {
      next();
    }
  }
});

export function routerPush(to: RouteLocationRaw) {
  router.push(to);
}

export function routerReplace(to: RouteLocationRaw) {
  router.replace(to);
}

export function routerBack() {
  router.back();
}

export function routerForward() {
  router.forward();
}

export function routerGo(delta: number) {
  router.go(delta);
}

export default router;
